//撤离点防守逻辑
params ["_pos"];

//不能与现有玩家同名
private _name = "";
private _curNames = [];
{
	_curNames pushBack (name _x);
}forEach AllPlayers;

while{true}do{
	_name = selectRandom asn_npc;
	if(!(_name in _curNames))exitWith{}; 
};

//组
private _group = createGroup east;//civilian;
//启用动态模拟
_group setVariable["no_cleanup", true];
_group enableDynamicSimulation true;

private _unit = _group createUnit ["O_T_Officer_F", _pos, [], 10, "NONE"];
_unit triggerDynamicSimulation false;
_unit setSkill 1;
//_unit setVariable ["FAR_SIDE_Medic", true, true];//不可以救玩家

_unit setVariable ["as_name", _name, true];
_unit setRank "LIEUTENANT";
//_unit setVariable ["as_level", "中尉", true];
as_units_sn pushBack _unit;
publicVariable "as_units_sn";


as_npc_red = _unit;
publicVariable "as_npc_red";

as_npc_red_hp = Param_Defend_HP;

//联络员 流血和死亡
[] spawn{
	private _t = time;
	while{alive as_npc_red}do{
		Sleep 1;
		if(lifeState as_npc_red != "INCAPACITATED")then{
			_t = time;
		}else{
			as_npc_red setVariable ["as_time", Param_Defend_Bleed - time + _t, true];
		};

		if(as_npc_red_hp < 0
		||{time > _t + Param_Defend_Bleed})then{
			as_npc_red setDamage 1.0;
		};
	};

	[east, "STR_TAG_O_9_0", "STR_TAG_O_9_1"] remoteExec ["fn_talk", east];
	[resistance, "联络员死亡", "联络员被我们干倒了！接下来就是严刑拷打！"] remoteExec ["fn_talk", resistance];
		
	as_game_restart = true;
};

//联络员被攻击
as_npc_red_t = time;

_unit addEventHandler ["HandleDamage", {
		params ["_unit", "_selection", "_damage", "_source", "_projectile", "_hitIndex", "_instigator", "_hitPoint"];
		if(alive _unit
			&& {lifeState _unit != "INCAPACITATED"})then{
			//设置为倒地状态
			_unit setUnconscious true;
			[east, "联络员", selectRandom ast_npc_red] remoteExec ["fn_talk", 0];
		};
		//伤害足够且5s触发一次
		if(_damage > 0.2
		&& {time > 5 + as_npc_red_t})then{as_npc_red_t = time;as_npc_red_hp = as_npc_red_hp - 1;};
		0
	}];


//等待玩家靠近
private _player = objNull;
waitUntil{Sleep 5;_player = ([getPos _unit, 10]call fn_getPlayerNear);!isNull _player};

//清理周围ai
[_pos, 2000] call fn_cleanupNear;

_unit lookAt _player;

//设置场景与镜头


if(Param_Defend_TP == 1)then{
	
	[["陆续的，队员们都到了撤离点……", "BLACK", 3]] remoteExec ["titleText", 0];
	Sleep 3;

	//触发支援 （容易导致ai不过来）
	//[_pos] call fn_aiNeedSupport;


	//朝南
	_unit lookAt (_unit getPos [10, 180]);
	_unit setDir 180;


	//位置计算
	private _dx = 1.2;
	private _sy = ((position _unit) select 1) - 4;
	private _sx = ((position _unit) select 0) - _dx * (count call fn_getPlayerRed) * 0.5;


	//传送玩家
	private _tps = call fn_getPlayerRed;


	{
		waitUntil{moveOut _x;Sleep 1;vehicle _x == _x};
		_x setPos [_sx + _dx * _forEachIndex, _sy];
		[_x, 0] remoteExec ["setDir", _x];
		[_x,"AmovPercMstpSlowWrflDnon_Salute"] remoteExec ["switchMove",0];
	}forEach _tps;


	Sleep 2;

	[1.0] remoteExec ["titleFadeOut", 0];
	//镜头
	[_unit, 12, 5, 4] remoteExec["fn_camToUnit", 0];


	Sleep 3;
};


[east, "STR_TAG_O_10_0", "STR_TAG_O_10_1"] remoteExec ["fn_talk", 0];
[_unit,"HubStanding_idle1"] remoteExec ["playMove",0];

//发钱
for "_i" from 1 to (count call fn_getPlayerRed) do{
	[_unit, Param_Defend_Money] call fn_putMoney;
	[_unit, Param_Defend_Money] call fn_putMoney;
	[_unit, Param_Defend_Money] call fn_putMoney;
	uiSleep 0.5;
};




uiSleep 10;

as_defend_state = 0;
publicVariable "as_defend_state";

[_unit,""] remoteExec ["switchMove",0];


//联络员跟随玩家
[] spawn{
	private _player = objNull;
	while{alive as_npc_red}do{
		//没有目标，或过远才找新玩家，或不在同一载具
		if((isNull _player) || {_player distance as_npc_red > 10} || {(vehicle _player != _player) &&{vehicle _player != vehicle as_npc_red}})then{
			_player = [getPos as_npc_red, 100] call fn_getPlayerNear;
		};
		if(!isNull _player)then{
			[group as_npc_red, _player] call fn_addWaypoint;
		}else{
			[group as_npc_red, getPos as_npc_red] call fn_addWaypoint;
		};
		Sleep 5;
	};
};


//开始防守
_group setBehaviour "COMBAT";

//装甲
[_pos] spawn{
	params ["_pos"];
	
	//轻装甲
	for "_i" from 1 to Param_Defend_Num_Easy do{
		Sleep 20;
		//突击队
		[0, selectRandom asg_easy, _pos, 600, 0, 1] spawn fn_createGN;
	};
	
	//重装甲
	for "_i" from 1 to Param_Defend_Num_Normal do{
		Sleep 45;
		//突击队
		[0, selectRandom asg_normal, _pos, 1000, 0, 1] spawn fn_createGN;
	};
};

//人员部队
for "_k" from 1 to Param_Defend_Num_Man do{
	private _group = [[_pos, 250, 50, false] call fn_getPosNearLand, 1.0, selectRandom[1,2,3,4,5,6], 10, selectRandom[0,1,2,3]] call fn_createGroup;
	_group setVariable["no_cleanup", true];
	[_group, _unit] spawn fn_addWaypointKeep;
};


//武直 + 固定翼
[0, asg_10, _pos, 1200, 0, 1] spawn fn_createGN;
[0, selectRandom[asg_21, asg_22], _pos, 1200, 0, 1] spawn fn_createGN;


"LeadTrack03_F_EXP" remoteExec ["playMusic"];

/*
[_pos, _unit]spawn{
	params ["_pos", "_unit"];
	//额外刷兵
	for "_i" from 1 to Param_Defend_Time do{
		for "_j" from 1 to Param_Defend_Num do{
			Sleep 1;
			private _group = [[_pos, 600, 100, false] call fn_getPosNearLand, 1.0, selectRandom[1,2,3,4,5,6], 10, selectRandom[0,1,2,3]] call fn_createGroup;
			_group setVariable["no_cleanup", true];
			[_group, _unit] spawn fn_addWaypointKeep;
			
			//突击队
			[0, selectRandom asg_easy, _pos, 1200, 0, 1] spawn fn_createGN;

		};
		
		if(random 100 < Param_Defend_Veh)then{
			[0, selectRandom asg_normal, _pos, 1200, 0, 1] spawn fn_createGN;
		};
		Sleep Param_Defend_Dt;
	};
};
*/

as_defend_state = 1;
publicVariable "as_defend_state";


//标记区域提示
"mk_escape" setMarkerShapeLocal "ELLIPSE";
"mk_escape" setMarkerSizeLocal [500, 500];		
"mk_escape" setMarkerColorLocal "ColorRed";
"mk_escape" setMarkerAlpha 0.2;

private _t = time;

//肃清触发
waitUntil{
	Sleep 60;
	private _numMan = {(side _x == resistance || {side _x == west})} count (_pos nearEntities [["Man"], 500]);
	private _list = _pos nearEntities [["Car", "Tank", "Air"], 600];
	private _numVeh = {(side _x == resistance || {side _x == west}) && {_x call fn_isArmed} } count _list;
	[_numMan, _numVeh] remoteExec ["fn_showNear", 0];
	(time > _t + 420) || {(_numMan < 25) && {_numVeh == 0}}
};


as_defend_state = 2;
publicVariable "as_defend_state";

//超时防守则出现红军武直
if(time > _t + 420)then{
	[_pos] spawn fn_mi48;
	Sleep 10;
	[_pos] spawn fn_mi48;
	Sleep 30;
};

_group setBehaviour "SAFE";

"mk_escape" setMarkerColorLocal "ColorWhite";
"mk_escape" setMarkerAlpha 0.5;

//mi 48
[_pos, "O_Heli_Attack_02_dynamicLoadout_F"] spawn fn_planeLand;

//PO-30
Sleep 20;
[_pos, "O_Heli_Light_02_dynamicLoadout_F"] spawn fn_planeLand;

//mi 290 长凳
Sleep 20;
[_pos, "O_Heli_Transport_04_bench_F"] spawn fn_planeLand;

//mi 290 运输
Sleep 20;
[_pos, "O_Heli_Transport_04_covered_F"] spawn fn_planeLand;

//西安
Sleep 20;
[_pos, "O_T_VTOL_02_infantry_dynamicLoadout_F"] spawn fn_planeLand;



[] spawn
{
	//0普通 1独自撤离
	as_end_state = 0;
	
	while{as_end_state == 0}do
	{
		Sleep 12;
		
		//地图外玩家添加操作（只能添加一次）
		{
			if ((!(_x getVariable ["escaped", false]))
				&& {(position _x) call fn_isOutMap}) then{
				
				_x remoteExec ["fnc_escaped", 0];	
				//[_x, localize "STR_TAG_O_2"] remoteExec ["sideChat", 0];
				_x setVariable ["escaped", true];
				
				_x remoteExec ["fnc_addAction", _x];
				
				//逃离次数 +1
				_x setVariable ["as_win", (_x getVariable ["as_win", 0]) + 1, true];
				[_x, "as_win", 0] call fn_savePlayerVar;
			};
		}forEach (call fn_getPlayerRed);
		
		//全部撤离（离开地图 或 高于100米）
		private _numAll = count call fn_getPlayerRed;
		private _num = {
			(((position _x) call fn_isOutMap) 
			|| {((position _x) select 2) > 50})
				} count (call fn_getPlayerRed);
		
		if(_num == _numAll)then{//&& {((position as_npc_red) call fn_isOutMap)}
			as_in_plane = true;
			publicVariable "as_in_plane";
			
			//完美完成+200
			if(((position as_npc_red) call fn_isOutMap) || {((position as_npc_red) select 2) > 50})then{
				{
					private _money =  _x getVariable["as_money", 0];
					_x setVariable ["as_money", _money + 300, true];
					
					//逃离次数 +1（额外加一次）
					_x setVariable ["as_win", (_x getVariable ["as_win", 0]) + 1, true];
					[_x, "as_win", 0] call fn_savePlayerVar;
					
				}forEach (call fn_getPlayerRed);
				remoteExec ["fnc_finish", 0];
			}else{
				[east, "STR_TAG_O_10_0", "我会将你们告上军事法庭！"] remoteExec ["fn_talk", east];
				Sleep 5;
			};

			{
				//逃离次数 +1（没有飞出地图）
				if(!(_x getVariable ["escaped", false]))then{
					_x setVariable ["as_win", (_x getVariable ["as_win", 0]) + 1, true];
					[_x, "as_win", 0] call fn_savePlayerVar;
				};
			}forEach (call fn_getPlayerRed);
			
			//
			[east, "STR_TAG_O_7_0", "STR_TAG_O_7_1"] remoteExec ["fn_talk", east];
			[resistance, "任务失败", "我们失去了Garvas上校，狡猾的敌人也逃跑了，我们应当以自杀谢罪，去追随他。"] remoteExec ["fn_talk", resistance];
			"Track_R_11" remoteExec ["playMusic"];//"LeadTrack03_F_Bootcamp" remoteExec ["playMusic", east];
			Sleep 25;
			as_game_restart = true;
			Sleep 60;//防止循环
		};
		
	};
	
	//部分撤离
	[east, "STR_TAG_O_8_0", "STR_TAG_O_8_1"] remoteExec ["fn_talk", east];
	[resistance, "任务失败", "我们留住了敌人的几名队员，但远远不能弥补失去Garvas上校的事实。"] remoteExec ["fn_talk", resistance];
	"LeadTrack03_F_Bootcamp" remoteExec ["playMusic", east];
	Sleep 15;
	as_game_restart = true;
	Sleep 60;//防止循环
};

